
var GLOBAL = {
  jsonp:     'callback=?',
  server:    'http://192.168.0.1',
  threshold: 3,
  size:      10,
  cutlength: 24,
  sort:      'updated',
};

var cPlusHome = function(bool){
  var isHome = $(location).attr('href').indexOf('home.jsp') == -1 ? false : true;
  var url = GLOBAL.server + '/threads'
      + '?threshold=' + GLOBAL.threshold
      + '&size=' + GLOBAL.size
      + '&sort=' + GLOBAL.sort
      + '&' + GLOBAL.jsonp;

  if(isHome && bool){
    cPlusGetJSON(url,
      function(data){
        var entries = '';
        for(var i = 0; i < data.threads.length; i++){
            var tweet = data.threads[i].tweet.replace(/<.*?>/g,'');
            var link = data.threads[i].url;
            var count = data.threads[i].replyCount;
            entries += '<p><a href="' + link + '&' + count + '">' + jpSubstr(tweet, GLOBAL.cutlength) + '...(' + count + ')</a></p>';
        }
        $('<div class="profileSection"><p>')
          .append('<div class="vfButtonBar"><h3>ChatterPLUS - HotEntry</h3></div>')
          .append('<div class="entitiesList">')
          .append(entries)
          .append('</div>')
          .append('</p></div>')
        .appendTo(".leftContent");
    });
  }
}

var cPlusProfile = function(bool){
  var isProfile = $(location).attr('href').indexOf('UserProfilePage') == -1 ? false : true;
  var mailAddr = $('.emailAddr > a').text();
  var url = GLOBAL.server + '/users/' + mailAddr + '?' + GLOBAL.jsonp;

  if(isProfile && bool){
    cPlusGetJSON(url,
      function(data){
        $('<div class="profileSection">')
          .append('<div class="vfButtonBar"><h3>ChatterPLUS - Profile</h3></div>')
          .append('<div class="aboutMe profileSectionBody">')
          .append('ツイート数: ' + data.user.count + '<br/>')
          .append('フォロー数: ' + data.user.followings + '<br/>')
          .append('フォロワ数: ' + data.user.followers + '<br/>')
          .append('</div>')
          .append('</div>')
        .appendTo(".leftContent");
    });
  }
}

function jpSubstr(str, len){
  var currentLength = 0;
  var incLength = 0;
  var estr = escape(str);
  for(var i = 0; i < estr.length; i++, currentLength++, incLength++){
    if(estr.charAt(i) == "%"){
      if(estr.charAt(++i) == "u"){
        i += 3;
        currentLength++;
      }
      i++;
    }
    if(currentLength >= len){
      return str.substr(0, incLength);
    }
  }
  return str;
}

var cPlusGetJSON = function(url, callback) {
  chrome.extension.sendRequest({action:'getJSON',url:url}, callback);
}

